const express = require('express');
const router = express.Router();
const pool = require('../models/database'); // 你自己的数据库连接配置

// 查询宠物帖子接口
router.get('/petPosts', async (req, res) => {
  try {
    const connection = await pool.getConnection();

    // 查询状态为1（已发布）的宠物帖子，按创建时间倒序
    const [rows] = await connection.query(
      `SELECT id, post_type, name, description, city, views, image_urls, status, created_at, updated_at
       FROM pet_posts WHERE status = 1 ORDER BY created_at DESC`
    );

    connection.release();

    const data = rows.map(row => ({
      ...row,
      image_urls: row.image_urls
    }));

    res.json({
      code: 200,
      message: '查询成功',
      data
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

// 发布宠物帖子
router.post('/create', async (req, res) => {
  const {
    post_type,
    name,
    description,
    city,
    image_urls,
    status
  } = req.body;

  // 基本校验
  if (!post_type || !name || !description || !city || !Array.isArray(image_urls)) {
    return res.status(400).json({
      code: 400,
      message: '缺少必要参数或格式错误'
    });
  }

  try {
    const connection = await pool.getConnection();

    // 插入数据
    const [result] = await connection.query(
      `INSERT INTO pet_posts (post_type, name, description, city, views, image_urls, status)
       VALUES (?, ?, ?, ?, 0, ?, ?)`,
      [post_type, name, description, city, JSON.stringify(image_urls), status]
    );

    connection.release();

    res.json({
      code: 200,
      message: '发布成功',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('发布出错:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
});


module.exports = router;
